﻿using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.SharePoint;
using MoveToSPList.Properties;

namespace MoveToSPList
{
    class Program
    {
        /// <summary>
        /// Точка входа программы
        /// </summary>
        static void Main(string[] args)
        {
            if (!IsDirectoryExist(Settings.Default.WatchedFolder) || 
                !IsWebAndListExist(Settings.Default.SharepointUrl,Settings.Default.SharepointListName))  
                return;            

            ProcessExistFiles();
            FileSystemWatcher fsw = new FileSystemWatcher(Settings.Default.WatchedFolder, "*.xml");
            fsw.Created += new FileSystemEventHandler(fsw_Created);
            fsw.EnableRaisingEvents = true;

            Console.WriteLine("SharePoint sync toy.");
            Console.WriteLine("Hit any key to exit.");
            Console.ReadKey();            
        }

      
        /// <summary>
        /// Обрабатываем уже существующие файлы
        /// </summary>
        private static void ProcessExistFiles()
        {
            string[] files = Directory.GetFiles(Settings.Default.WatchedFolder, "*.xml");
            Dictionary<string, string> fieldsMappingDictionary = new Dictionary<string, string>();
            foreach (string item in Settings.Default.MappingDictionary)
            {
                string[] h = item.Split(new char[] { '=' });
                fieldsMappingDictionary.Add(h[0], h[1]);
            }
            foreach (string filePath in files)
            {

                
                    MoveData.MoveFromXmlToSPList(filePath,
                        Settings.Default.SharepointUrl,
                        Settings.Default.SharepointListName,
                        fieldsMappingDictionary,
                        Settings.Default.SharepointKeyField,
                        Settings.Default.XmlKeyField);                
                
            }
        }
        /// <summary>
        /// Обработчик события добавления файла в наблюдаемую папку.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void fsw_Created(object sender, FileSystemEventArgs e)
        {
            Dictionary<string, string> fieldsMappingDictionary = new Dictionary<string, string>();
            foreach (string item in Settings.Default.MappingDictionary)
            {
                string[] h = item.Split(new char[] { '=' });
                fieldsMappingDictionary.Add(h[0], h[1]);
            }

            MoveData.MoveFromXmlToSPList(e.FullPath,
                Settings.Default.SharepointUrl,
                Settings.Default.SharepointListName, 
                fieldsMappingDictionary,
                Settings.Default.SharepointKeyField,
                Settings.Default.XmlKeyField);
        }     
        /// <summary>
        /// Проверяем наличие узла и списка.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="listname"></param>
        /// <returns></returns>
        private static bool IsWebAndListExist(string path,string listname)
        {
            using (SPSite site = new SPSite(path))
            using (SPWeb web = site.OpenWeb())
            {
                if (web == null)
                {
                    Console.WriteLine("Отсутствует узел SharePoint. Проверьте файл настроек.");
                    return false;
                }
                foreach (SPList item in web.Lists)
                    if (item.Title.Equals(listname))
                        return true;
                return false;
            }  
        }
        /// <summary>
        /// Проверка наличия директории, куда попадают файлы 
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private static bool IsDirectoryExist(string path)
        {
        bool ret = false;
          if(!Directory.Exists(path))
            Console.WriteLine("Отсутствует папка с xml файлами. Проверьте файл настроек.");
          else
ret = true;
return ret;
        }                    
    }
}
